package com.uniview.interceptor;

import com.uniview.constants.CommonConstants;
import com.uniview.eumn.CommonEnum;
import com.uniview.exception.CommonException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * created by lux
 * 全局校验器，校验请求是否来自网关
 */
@Component
public class GlobalInterceptor implements HandlerInterceptor {
    @Autowired
    RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //校验请求头里面的X-Request-Id
        String secretKey  = request.getHeader(CommonConstants.X_REQUEST_ID);
        //校验redis里面是否存在这个值，如果存在则续期该key一分钟（设置时间不能太长，防止高并发时太多值干扰）
        if(!secretKey.equals(redisTemplate.opsForValue().get(CommonConstants.X_REQUEST_ID))){
            throw new CommonException(CommonEnum.GATEWAY_ERROR_CODE,CommonEnum.GATEWAY__ERROR_MSG);
        }
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {

    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,@Nullable Exception ex) throws Exception {

    }
}
